package com.bdqn.servlet.sysuser;

import com.bdqn.pojo.SysUser;
import com.bdqn.service.SysUserService;
import com.bdqn.service.impl.SysUserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * ListServlet
 *
 * @author LILIBO
 * @since 2024/7/3
 */
@WebServlet("/sys/user/list")
public class ListServlet extends HttpServlet {

    /**
     * 引入业务逻辑层
     */
    private final SysUserService sysUserService = new SysUserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 检查用户是否登录
        SysUser sysUser = (SysUser) request.getSession().getAttribute("userSession");
        if (sysUser == null) { // 用户未登录，跳转到登录页
            response.sendRedirect("login");
            return;
        }
        // 获取页面参数
        String queryRealName = request.getParameter("queryRealName");
        String queryRoleIdStr = request.getParameter("queryRoleId");
        Long queryRoleId = queryRoleIdStr == null ? 0 : Long.valueOf(queryRoleIdStr);
        String pageIndexStr = request.getParameter("pageIndex");
        Long pageIndex = pageIndexStr == null ? 1 : Long.valueOf(pageIndexStr);
        Long pageSize = 5L;

        // 根据条件查询总数量
        long totalCount = sysUserService.countPage(queryRealName, queryRoleId);
        long totalPageCount = (totalCount % pageSize == 0) ? (totalCount / pageSize) : (totalCount / pageSize + 1);
        // 调用业务逻辑层获取分页数据
        List<SysUser> userList = sysUserService.selectPage(queryRealName, queryRoleId, pageIndex, pageSize);
        // 将数据设置到作用域
        request.setAttribute("userList", userList);
        request.setAttribute("totalCount", totalCount);
        request.setAttribute("totalPageCount", totalPageCount);
        request.setAttribute("queryRealName", queryRealName);
        request.setAttribute("currentPageNo", pageIndex);
        request.setAttribute("pageIndex", pageIndex);

        // 跳转页面
        request.getRequestDispatcher("jsp/sysUser/list.jsp").forward(request, response);
    }

}
